﻿using ArcGIS.Core.Data;
using ArcGIS.Core.Data.UtilityNetwork.Trace;
using ArcGIS.Core.Geometry;
using ArcGIS.Desktop.Core;
using ArcGIS.Desktop.Framework.Threading.Tasks;
using ArcGIS.Desktop.Layouts;
using ArcGIS.Desktop.Mapping;
using Aspose.Cells;
using CCTool.Scripts.CusTool3;
using CCTool.Scripts.Manager;
using CCTool.Scripts.ToolManagers;
using CCTool.Scripts.ToolManagers.Extensions;
using CCTool.Scripts.ToolManagers.Managers;
using Microsoft.Office.Core;
using Microsoft.VisualBasic;
using NPOI.OpenXmlFormats.Vml;
using NPOI.SS.Formula.Functions;
using NPOI.SS.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Geometry = ArcGIS.Core.Geometry.Geometry;
using Path = System.IO.Path;
using Polygon = ArcGIS.Core.Geometry.Polygon;
using Row = ArcGIS.Core.Data.Row;
using Table = ArcGIS.Core.Data.Table;

namespace CCTool.Scripts.UI
{
    /// <summary>
    /// Interaction logic for ZQZB.xaml
    /// </summary>
    public partial class ZQZB : ArcGIS.Desktop.Framework.Controls.ProWindow
    {
        public ZQZB()
        {
            InitializeComponent();
        }

        // 定义一个进度框
        private ProcessWindow processwindow = null;
        string tool_name = "镇区划定";

        string defGDB = Project.Current.DefaultGeodatabasePath;
        string defFolder = Project.Current.HomeFolderPath;

        List<string> years = new List<string>() { "2021", "2022", "2023", "2024" };
        List<string> years2 = new List<string>() { "2021" };
        // 行政区边界    
        string xzqFolder = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\分镇区基础GDB";


        // 输入文件夹
        string inputFolder = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\【标准成果数据】";

        string newInputFolder = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\【标准成果数据】第二轮";

        // 行政区代码和名称
        Dictionary<string, string> dict_xzq = new Dictionary<string, string>()
        {
            {"剑斗镇", "350524011"}, {"感德镇", "350524012"}, {"湖头镇", "350524013"}, {"金谷镇", "350524014"}, {"蓬莱镇", "350524015"},
            {"魁斗镇", "350524016"}, {"凤城镇", "350524017"}, {"芦田镇", "350524018"}, {"西坪镇", "350524019"}, {"官桥镇", "350524020"},
            {"虎邱镇", "350524021"}, {"龙门镇", "350524022"}, {"城厢镇", "350524023"}, {"长卿镇", "350524024"}, {"祥华乡", "350524025"},
            {"蓝田乡", "350524026"}, {"尚卿乡", "350524027"}, {"参内镇", "350524028"}, {"龙涓乡", "350524029"}, {"大坪乡", "350524030"},
            {"福田乡", "350524031"}, {"白濑乡", "350524032"}, {"湖上乡", "350524033"}, {"桃舟乡", "350524034"},
        };

        // 计算镇区范围
        private async void btn_zqfw_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    string gdb = $@"{inputFolder}\350524安溪县\350524安溪县2021\1矢量数据\350524安溪县.gdb";

                    // 获取 矢量数据
                    List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                    // 记录镇区村比例
                    List<List<string>> blList = new List<List<string>>();

                    // 指标
                    Dictionary<string, List<double>> dict = new Dictionary<string, List<double>>();

                    foreach (var fc in fcs)
                    {
                        // 找zqfw
                        if (!fc.Contains("zqfw"))
                        {
                            continue;
                        }

                        string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                        // 行政区名称
                        string zName = fcName.GetWord("中文");
                        string zCode = dict_xzq.ContainsKey(zName) ? dict_xzq[zName] : "";

                        // 各个镇指标
                        List<string> zzb = new List<string>();


                        pw.AddMessageMiddle(0, $"{zCode}{zName}", Brushes.Gray);

                        // 镇区范围
                        string zqfw = fc;
                        // 实体地域
                        string zqstdy = fc.Replace("zqfw", "zqstdy");
                        // 行政区边界
                        string xzqbj = $@"{xzqFolder}\{zCode}{zName}\2021\{zCode}{zName}.gdb\村级调查区";
                        string dltb = $@"{xzqFolder}\{zCode}{zName}\2021\{zCode}{zName}.gdb\地类图斑";

                        // 更新村庄名称和代码
                        UpdataCZName(zqfw, xzqbj);


                        // 统计
                        string statistics_stdy = $@"{defGDB}\statistics_stdy";
                        Arcpy.TabulateIntersection(xzqbj, new List<string>() { "ZLDWMC" }, zqstdy, statistics_stdy, "");

                        string statistics_total = $@"{defGDB}\statistics_total";
                        string tb_total = $@"{defGDB}\tb_total";    // 指定地类
                        Arcpy.Select(dltb, tb_total, "CZCSXM IN ('202', '202A', '203', '203A') Or DLBM IN ('1001', '1002', '1003', '1006', '1007', '1008', '1009', '1107', '1107A', '1109')");
                        Arcpy.TabulateIntersection(xzqbj, new List<string>() { "ZLDWMC" }, tb_total, statistics_total, "");

                        // 指标提取
                        Dictionary<string, double> dict_stdy = GisTool.GetDictFromPathDouble(statistics_stdy, "ZLDWMC", "AREA");
                        Dictionary<string, double> dict_total = GisTool.GetDictFromPathDouble(statistics_total, "ZLDWMC", "AREA");

                        foreach (var item in dict_total)
                        {
                            // 实体地域面积
                            double stdy_area = dict_stdy.ContainsKey(item.Key) ? dict_stdy[item.Key] : 0;

                            if (!dict.ContainsKey(item.Key))
                            {
                                dict.Add(item.Key, new List<double>() { item.Value, stdy_area });
                            }
                            dict[item.Key] = new List<double>() { item.Value, stdy_area };
                        }

                        // 指标更新到镇区范围图层
                        Table table = zqfw.TargetTable();
                        using RowCursor cursor = table.Search();
                        while (cursor.MoveNext())
                        {
                            using Row row = cursor.Current;
                            string jcwmc = row["JCWMC"]?.ToString();
                            string jcwdm = row["JCWDM"]?.ToString();
                            foreach (var item in dict)
                            {
                                if (item.Key == jcwmc)
                                {
                                    row["ZDDLMJ"] = item.Value[0];
                                    row["STDYMJ"] = item.Value[1];
                                    row["MJZB"] = item.Value[1] / item.Value[0];
                                    row["XZQDM"] = zCode;
                                    row["XZQMC"] = zName;
                                    row["SMC"] = "福建省";

                                    row["BZ"] = "";
                                    row["BHBZ"] = "";
                                    row["JCWMJ"] = (double)row["Shape_Area"];

                                    row.Store();

                                    blList.Add(new List<string>() { zName, jcwmc, jcwdm, $"{item.Value[0]}", $"{item.Value[1]}", $"{item.Value[1] / item.Value[0]}" });
                                    break;
                                }
                            }

                        }

                    }

                    // 写入excel表格
                    WriteExcel(blList);



                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }

        }

        private void WriteExcel(List<List<string>> blList)
        {
            string sourceExcelPath = $@"C:\Users\Administrator\Desktop\最小统计单元面积表.xlsx";
            string excelPath = $@"C:\Users\Administrator\Desktop\最小统计单元面积表_导出.xlsx";
            File.Copy(sourceExcelPath, excelPath, true);

            // 获取工作薄、工作表
            string excelFile = ExcelTool.GetPath(excelPath);
            int sheetIndex = ExcelTool.GetSheetIndex(excelPath);
            // 打开工作薄
            Workbook wb = ExcelTool.OpenWorkbook(excelFile);
            // 打开工作表
            Worksheet sheet = wb.Worksheets[sheetIndex];
            // 获取cell
            Cells cells = sheet.Cells;
            for (int i = 0; i < blList.Count; i++)
            {
                if (i > 0)
                {
                    cells.CopyRow(cells, 1, i + 1);
                }
                cells[i + 1, 0].Value = i + 1;
                cells[i + 1, 1].Value = blList[i][0];
                cells[i + 1, 2].Value = blList[i][1];
                cells[i + 1, 3].Value = blList[i][2];
                cells[i + 1, 4].Value = blList[i][3].ToDouble();
                cells[i + 1, 5].Value = blList[i][4].ToDouble();
                cells[i + 1, 6].Value = blList[i][5].ToDouble();
            }

            // 保存
            wb.Save(excelFile);
            wb.Dispose();


        }

        private void UpdataCZName(string zqfw, string xzqbj)
        {
            // 获取原始图层和标识图层的要素类
            FeatureClass originFeatureClass = zqfw.TargetFeatureClass();
            FeatureClass identityFeatureClass = xzqbj.TargetFeatureClass();

            // 获取目标图层和源图层的要素游标
            using RowCursor originCursor = originFeatureClass.Search();

            // 遍历源图层的要素
            while (originCursor.MoveNext())
            {

                using Feature originFeature = (Feature)originCursor.Current;

                // 获取源要素的几何
                ArcGIS.Core.Geometry.Geometry originGeometry = originFeature.GetShape();

                // 创建空间查询过滤器，以获取与源要素有重叠的目标要素
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry = originGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // 在目标图层中查询与源要素重叠的要素
                using (RowCursor identityCursor = identityFeatureClass.Search(spatialFilter))
                {
                    while (identityCursor.MoveNext())
                    {
                        using Feature identityFeature = (Feature)identityCursor.Current;
                        // 获取目标要素的几何
                        ArcGIS.Core.Geometry.Geometry identityGeometry = identityFeature.GetShape();

                        // 计算源要素与目标要素的重叠面积
                        ArcGIS.Core.Geometry.Geometry intersection = GeometryEngine.Instance.Intersection(originGeometry, identityGeometry);

                        // 如果重叠面积大于当前最大重叠面积，则更新最大重叠面积和目标要素
                        if (intersection is not null)
                        {
                            double overlapArea = Math.Round((intersection as ArcGIS.Core.Geometry.Polygon).Area, 2);

                            if (overlapArea > 0)
                            {
                                // 赋值
                                originFeature["JCWMC"] = identityFeature["ZLDWMC"];
                                originFeature["JCWDM"] = identityFeature["ZLDWDM"];
                            }

                        }
                    }
                }

                // 更新源图层中的源要素
                originFeature.Store();

            }
        }

        private async void btn_cs_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"【{year}】", Brushes.Blue);

                        string gdbPath = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdbPath.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            // 找zqcsfw
                            if (!fc.Contains("zqcsfw"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                            // 行政区名称
                            string zName = fcName.GetWord("中文");
                            string zCode = dict_xzq.ContainsKey(zName) ? dict_xzq[zName] : "";

                            pw.AddMessageMiddle(0, $"{zCode}{zName}", Brushes.Gray);

                            // 镇区初始范围
                            string zqcsfw = fc;
                            // 重新计算字段
                            Arcpy.CalculateField(zqcsfw, "XZQDM", $"'{zCode}'");
                            Arcpy.CalculateField(zqcsfw, "XZQMC", $"'{zName}'");
                            Arcpy.CalculateField(zqcsfw, "SMC", "'福建省'");
                            Arcpy.CalculateField(zqcsfw, "JSMJ", "round(!Shape_Area!,2)");
                            Arcpy.CalculateField(zqcsfw, "BZ", "''");

                        }
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }



        // 测试按钮
        private async void btn_test_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    string year = "2024";

                    string gdb = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\【标准成果数据】\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                    // 获取 矢量数据
                    List<string> fcs = gdb.GetFeatureClassPathFromGDB();



                    // 指标
                    Dictionary<string, List<double>> dict = new Dictionary<string, List<double>>();

                    List<string> lxs = new List<string>()
                    {
                        "zqstdyjstb","zqstdyzjtb",
                    };

                    List<string> lxs2 = new List<string>()
                    {
                        "zqcsfw","zqstdy","zqstdyjstb","zqstdyzjtb",
                    };

                    foreach (var lx in lxs2)
                    {
                        pw.AddMessageMiddle(0, $"【{year}、{lx}】", Brushes.Blue);

                        List<string> merge = new List<string>();

                        foreach (var fc in fcs)
                        {
                            // 找zqstdy
                            if (fc.EndsWith(lx))
                            {
                                merge.Add(fc);
                            }
                        }

                        Arcpy.Merge(merge, $@"{defGDB}\安溪县{lx}", true);
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }

        }

        private async void btn_zqfw_fd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\zqfw";

                    string gdb = $@"{inputFolder}\350524安溪县\350524安溪县2021\1矢量数据\350524安溪县.gdb";

                    // 获取 矢量数据
                    List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                    foreach (var fc in fcs)
                    {
                        // 找zqfw
                        if (!fc.Contains("zqfw"))
                        {
                            continue;
                        }

                        string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                        pw.AddMessageMiddle(0, $"{fcName}", Brushes.Gray);

                        // 通过模板更新所有字段
                        string tem = $@"{defGDB}\tem";
                        Arcpy.CopyFeatures(model, tem);
                        Arcpy.Append(fc, tem);
                        Arcpy.CopyFeatures(tem, fc);

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_cs_fd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\zqcsfw";

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"【{year}】", Brushes.Blue);

                        string gdbPath = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdbPath.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            // 找zqcsfw
                            if (!fc.Contains("zqcsfw"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];
                            pw.AddMessageMiddle(0, $"{fcName}", Brushes.Gray);

                            // 通过模板更新所有字段
                            string tem = $@"{defGDB}\tem";
                            Arcpy.CopyFeatures(model, tem);
                            Arcpy.Append(fc, tem);
                            Arcpy.CopyFeatures(tem, fc);
                        }
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_stdy_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"【{year}】", Brushes.Blue);

                        string gdbPath = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdbPath.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            // 找zqstdy
                            if (!fc.EndsWith("zqstdy"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                            // 行政区名称
                            string zName = fcName.GetWord("中文");
                            string zCode = dict_xzq.ContainsKey(zName) ? dict_xzq[zName] : "";

                            pw.AddMessageMiddle(0, $"{zCode}{zName}", Brushes.Black);

                            // 行政区边界
                            string xzqbj = $@"{xzqFolder}\{zCode}{zName}\2021\{zCode}{zName}.gdb\村级调查区";
                            string dltb = $@"{xzqFolder}\{zCode}{zName}\{year}\{zCode}{zName}.gdb\地类图斑";

                            // 重新计算字段
                            Arcpy.CalculateField(fc, "XZQDM", $"'{zCode}'");
                            Arcpy.CalculateField(fc, "XZQMC", $"'{zName}'");
                            Arcpy.CalculateField(fc, "SMC", "'福建省'");
                            Arcpy.CalculateField(fc, "TSQK", "''");
                            Arcpy.CalculateField(fc, "BHBZ", "''");
                            Arcpy.CalculateField(fc, "BZ", "''");
                            Arcpy.CalculateField(fc, "RepeatNum", "'3'");

                            pw.AddMessageMiddle(0, $"      更新村庄名称和代码", Brushes.Gray);
                            // 更新村庄名称和代码
                            UpdataCZNameAndDLMC(fc, dltb);

                            // 更新迭代次数
                            pw.AddMessageMiddle(0, $"      更新迭代次数1", Brushes.Gray);
                            // 初始范围
                            string zqcsfw = fc.Replace("zqstdy", "zqcsfw");
                            UpdataNum00(fc, zqcsfw);
                            pw.AddMessageMiddle(0, $"      更新迭代次数2", Brushes.Gray);
                            // 1迭代
                            string bj_fc = $@"{defGDB}\bj_fc";
                            UpdataNum01(fc, zqcsfw, bj_fc);
                            pw.AddMessageMiddle(0, $"      更新迭代次数3", Brushes.Gray);
                            // 2迭代
                            UpdataNum02(fc, bj_fc);

                        }
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }


        // 初始范围
        private void UpdataNum00(string fc, string zqcsfw)
        {

            // 获取原始图层和标识图层的要素类
            FeatureClass originFeatureClass = fc.TargetFeatureClass();
            FeatureClass identityFeatureClass = zqcsfw.TargetFeatureClass();

            // 获取目标图层和源图层的要素游标
            using RowCursor originCursor = originFeatureClass.Search();

            // 遍历源图层的要素
            while (originCursor.MoveNext())
            {

                using Feature originFeature = (Feature)originCursor.Current;

                // 获取源要素的几何
                ArcGIS.Core.Geometry.Geometry originGeometry = originFeature.GetShape();

                // 创建空间查询过滤器，以获取与源要素有重叠的目标要素
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry = originGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // 在目标图层中查询与源要素重叠的要素
                using (RowCursor identityCursor = identityFeatureClass.Search(spatialFilter))
                {
                    while (identityCursor.MoveNext())
                    {

                        using Feature identityFeature = (Feature)identityCursor.Current;
                        // 获取目标要素的几何
                        ArcGIS.Core.Geometry.Geometry identityGeometry = identityFeature.GetShape();

                        // 计算源要素与目标要素的重叠面积
                        ArcGIS.Core.Geometry.Geometry intersection = GeometryEngine.Instance.Intersection(originGeometry, identityGeometry);

                        // 如果重叠面积大于当前最大重叠面积，则更新最大重叠面积和目标要素
                        if (intersection is not null)
                        {
                            double overlapArea = Math.Round((intersection as ArcGIS.Core.Geometry.Polygon).Area, 2);

                            if (overlapArea > 0)
                            {
                                // 赋值
                                originFeature["RepeatNum"] = "0";

                                // 更新源图层中的源要素
                                originFeature.Store();
                            }
                        }
                    }
                }



            }


        }

        // 1迭代
        private void UpdataNum01(string fc, string zqcsfw, string bj_fc)
        {
            string defGDB = Project.Current.DefaultGeodatabasePath;

            string buffer = $@"{defGDB}\buffer";
            // 缓冲
            Arcpy.Buffer(zqcsfw, buffer, "100 Meters");

            // 获取原始图层和标识图层的要素类
            FeatureClass originFeatureClass = fc.TargetFeatureClass();
            FeatureClass identityFeatureClass = buffer.TargetFeatureClass();

            // 获取目标图层和源图层的要素游标
            using RowCursor originCursor = originFeatureClass.Search();

            // 遍历源图层的要素
            while (originCursor.MoveNext())
            {

                using Feature originFeature = (Feature)originCursor.Current;

                string bj = originFeature["RepeatNum"]?.ToString() ?? "3";

                // 获取源要素的几何
                ArcGIS.Core.Geometry.Geometry originGeometry = originFeature.GetShape();

                // 创建空间查询过滤器，以获取与源要素有重叠的目标要素
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry = originGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // 在目标图层中查询与源要素重叠的要素
                using (RowCursor identityCursor = identityFeatureClass.Search(spatialFilter))
                {
                    while (identityCursor.MoveNext())
                    {

                        using Feature identityFeature = (Feature)identityCursor.Current;
                        // 获取目标要素的几何
                        ArcGIS.Core.Geometry.Geometry identityGeometry = identityFeature.GetShape();

                        // 计算源要素与目标要素的重叠面积
                        ArcGIS.Core.Geometry.Geometry intersection = GeometryEngine.Instance.Intersection(originGeometry, identityGeometry);

                        // 如果重叠面积大于当前最大重叠面积，则更新最大重叠面积和目标要素
                        if (intersection is not null && bj != "0")
                        {
                            double overlapArea = Math.Round((intersection as ArcGIS.Core.Geometry.Polygon).Area, 2);

                            if (overlapArea > 0)
                            {
                                // 赋值
                                originFeature["RepeatNum"] = "1";

                                // 更新源图层中的源要素
                                originFeature.Store();
                            }
                        }
                    }
                }

            }

            // 提取更新后的矢量
            Arcpy.Select(fc, bj_fc, "RepeatNum IN ('0', '1')");

        }

        // 2迭代
        private void UpdataNum02(string fc, string bj_fc)
        {
            string defGDB = Project.Current.DefaultGeodatabasePath;

            string buffer = $@"{defGDB}\buffer";
            // 缓冲
            Arcpy.Buffer(bj_fc, buffer, "100 Meters");

            // 获取原始图层和标识图层的要素类
            FeatureClass originFeatureClass = fc.TargetFeatureClass();
            FeatureClass identityFeatureClass = buffer.TargetFeatureClass();

            // 获取目标图层和源图层的要素游标
            using RowCursor originCursor = originFeatureClass.Search();

            // 遍历源图层的要素
            while (originCursor.MoveNext())
            {

                using Feature originFeature = (Feature)originCursor.Current;

                string bj = originFeature["RepeatNum"]?.ToString() ?? "3";

                // 获取源要素的几何
                ArcGIS.Core.Geometry.Geometry originGeometry = originFeature.GetShape();

                // 创建空间查询过滤器，以获取与源要素有重叠的目标要素
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry = originGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // 在目标图层中查询与源要素重叠的要素
                using (RowCursor identityCursor = identityFeatureClass.Search(spatialFilter))
                {
                    while (identityCursor.MoveNext())
                    {

                        using Feature identityFeature = (Feature)identityCursor.Current;
                        // 获取目标要素的几何
                        ArcGIS.Core.Geometry.Geometry identityGeometry = identityFeature.GetShape();

                        // 计算源要素与目标要素的重叠面积
                        ArcGIS.Core.Geometry.Geometry intersection = GeometryEngine.Instance.Intersection(originGeometry, identityGeometry);

                        // 如果重叠面积大于当前最大重叠面积，则更新最大重叠面积和目标要素
                        if (intersection is not null && bj != "0" && bj != "1")
                        {
                            double overlapArea = Math.Round((intersection as ArcGIS.Core.Geometry.Polygon).Area, 2);

                            if (overlapArea > 0)
                            {
                                // 赋值
                                originFeature["RepeatNum"] = "2";

                                // 更新源图层中的源要素
                                originFeature.Store();
                            }
                        }
                    }
                }
            }
        }

        private void UpdataCZNameAndDLMC(string fc, string dltb)
        {
            string clip_dltb = $@"{defGDB}\clip_dltb";
            Arcpy.Clip(dltb, fc, clip_dltb);

            // 获取原始图层和标识图层的要素类
            FeatureClass originFeatureClass = fc.TargetFeatureClass();
            FeatureClass identityFeatureClass = clip_dltb.TargetFeatureClass();

            // 获取目标图层和源图层的要素游标
            using RowCursor originCursor = originFeatureClass.Search();

            // 遍历源图层的要素
            while (originCursor.MoveNext())
            {

                using Feature originFeature = (Feature)originCursor.Current;

                // 获取源要素的几何
                ArcGIS.Core.Geometry.Geometry originGeometry = originFeature.GetShape();

                // 创建空间查询过滤器，以获取与源要素有重叠的目标要素
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry = originGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // 在目标图层中查询与源要素重叠的要素
                using (RowCursor identityCursor = identityFeatureClass.Search(spatialFilter))
                {
                    while (identityCursor.MoveNext())
                    {
                        double area = 0;

                        using Feature identityFeature = (Feature)identityCursor.Current;
                        // 获取目标要素的几何
                        ArcGIS.Core.Geometry.Geometry identityGeometry = identityFeature.GetShape();

                        // 计算源要素与目标要素的重叠面积
                        ArcGIS.Core.Geometry.Geometry intersection = GeometryEngine.Instance.Intersection(originGeometry, identityGeometry);

                        // 如果重叠面积大于当前最大重叠面积，则更新最大重叠面积和目标要素
                        if (intersection is not null)
                        {
                            double overlapArea = Math.Round((intersection as ArcGIS.Core.Geometry.Polygon).Area, 2);

                            if (overlapArea > area)
                            {
                                // 赋值
                                originFeature["JCWMC"] = identityFeature["ZLDWMC"];
                                originFeature["JCWDM"] = identityFeature["ZLDWDM"];
                                originFeature["DLMC"] = identityFeature["DLMC"];
                                originFeature["DLBM"] = identityFeature["DLBM"];

                                area = overlapArea;
                            }
                        }
                    }
                }

                // 更新源图层中的源要素
                originFeature.Store();

            }
        }


        private async void btn_stdy_fd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\zqstdy";

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"【{year}】", Brushes.Blue);

                        string gdbPath = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdbPath.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            // 找zqstdy
                            if (!fc.EndsWith("zqstdy"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];
                            pw.AddMessageMiddle(0, $"{fcName}", Brushes.Gray);

                            // 通过模板更新所有字段
                            string tem = $@"{defGDB}\tem";
                            Arcpy.CopyFeatures(model, tem);
                            Arcpy.Append(fc, tem);
                            Arcpy.CopyFeatures(tem, fc);
                        }
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }


        private async void btn_xzjx_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    string gdb = $@"{inputFolder}\350524安溪县\350524安溪县2021\1矢量数据\350524安溪县.gdb";

                    // 获取 矢量数据
                    List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                    // 记录镇区村比例
                    List<List<string>> blList = new List<List<string>>();

                    // 指标
                    Dictionary<string, List<double>> dict = new Dictionary<string, List<double>>();

                    foreach (var fc in fcs)
                    {
                        // 找xzjx
                        if (!fc.Contains("xzjx"))
                        {
                            continue;
                        }

                        string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                        // 行政区名称
                        string zName = fcName.GetWord("中文");
                        string zCode = dict_xzq.ContainsKey(zName) ? dict_xzq[zName] : "";

                        pw.AddMessageMiddle(0, $"{zCode}{zName}", Brushes.Gray);


                        string xzjx = fc;

                        // 计算字段
                        Arcpy.CalculateField(xzjx, "XZQDM", $"'{zCode}'");
                        Arcpy.CalculateField(xzjx, "XZQMC", $"'{zName}'");
                        Arcpy.CalculateField(xzjx, "QXMC", "'安溪县'");
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }

        }

        private async void btn_xzjx_fd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\xzjx";

                    string gdb = $@"{inputFolder}\350524安溪县\350524安溪县2021\1矢量数据\350524安溪县.gdb";

                    // 获取 矢量数据
                    List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                    foreach (var fc in fcs)
                    {
                        // 找xzjx
                        if (!fc.Contains("xzjx"))
                        {
                            continue;
                        }

                        string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                        pw.AddMessageMiddle(0, $"{fcName}", Brushes.Gray);

                        // 通过模板更新所有字段
                        string tem = $@"{defGDB}\tem";
                        Arcpy.CopyFeatures(model, tem);
                        Arcpy.Append(fc, tem);
                        Arcpy.CopyFeatures(tem, fc);

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_tjdy_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    string gdb = $@"{inputFolder}\350524安溪县\350524安溪县2021\1矢量数据\350524安溪县.gdb";

                    // 获取 矢量数据
                    List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                    // 记录镇区村比例
                    List<List<string>> blList = new List<List<string>>();

                    // 指标
                    Dictionary<string, List<double>> dict = new Dictionary<string, List<double>>();

                    foreach (var fc in fcs)
                    {
                        // 找zxtjdy
                        if (!fc.Contains("zxtjdy"))
                        {
                            continue;
                        }

                        string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                        // 行政区名称
                        string zName = fcName.GetWord("中文");
                        string zCode = dict_xzq.ContainsKey(zName) ? dict_xzq[zName] : "";

                        pw.AddMessageMiddle(0, $"{zCode}{zName}", Brushes.Gray);


                        string xzjx = fc;

                        // 计算字段
                        Arcpy.CalculateField(xzjx, "XZQDM", $"'{zCode}'");
                        Arcpy.CalculateField(xzjx, "XZQMC", $"'{zName}'");

                        Arcpy.CalculateField(xzjx, "BZ", "''");


                        // 行政区边界
                        string xzqbj = $@"{xzqFolder}\{zCode}{zName}\2021\{zCode}{zName}.gdb\村级调查区";

                        // 更新村庄名称和代码
                        UpdataCZName(xzjx, xzqbj);

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }

        }

        private async void btn_tjdy_fd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\zxtjdy";

                    string gdb = $@"{inputFolder}\350524安溪县\350524安溪县2021\1矢量数据\350524安溪县.gdb";

                    // 获取 矢量数据
                    List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                    foreach (var fc in fcs)
                    {
                        // 找zxtjdy
                        if (!fc.Contains("zxtjdy"))
                        {
                            continue;
                        }

                        string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                        pw.AddMessageMiddle(0, $"{fcName}", Brushes.Gray);

                        // 通过模板更新所有字段
                        string tem = $@"{defGDB}\tem";
                        Arcpy.CopyFeatures(model, tem);
                        Arcpy.Append(fc, tem);
                        Arcpy.CopyFeatures(tem, fc);

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_zjtb_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");
                        string gdb = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";
                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            // 找zqstdyzjtb
                            if (!fc.Contains("zqstdyzjtb"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                            // 行政区名称
                            string zName = fcName.GetWord("中文");
                            string zCode = dict_xzq.ContainsKey(zName) ? dict_xzq[zName] : "";

                            pw.AddMessageMiddle(0, $"{zCode}{zName}", Brushes.Gray);


                            string zqstdyzjtb = fc;

                            // 计算字段
                            Arcpy.CalculateField(zqstdyzjtb, "TBZJ", $"'迭代纳入'");

                            Arcpy.CalculateField(zqstdyzjtb, "BZ", "''");

                            string dltb = zqstdyzjtb.Replace("zqstdyzjtb", "zqstdy");
                            // 更新村庄名称和代码
                            UpdataDLMC(zqstdyzjtb, dltb);

                        }
                    }
                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }

        }

        private async void btn_zjtb_fd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\zqstdyzjtb";

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");
                        string gdb = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            // 找zqstdyzjtb
                            if (!fc.Contains("zqstdyzjtb"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                            pw.AddMessageMiddle(0, $"{fcName}", Brushes.Gray);

                            // 通过模板更新所有字段
                            string tem = $@"{defGDB}\tem";
                            Arcpy.CopyFeatures(model, tem);
                            Arcpy.Append(fc, tem);
                            Arcpy.CopyFeatures(tem, fc);

                        }
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_jstb_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");
                        string gdb = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";
                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        // 记录镇区村比例
                        List<List<string>> blList = new List<List<string>>();

                        // 指标
                        Dictionary<string, List<double>> dict = new Dictionary<string, List<double>>();

                        foreach (var fc in fcs)
                        {
                            // 找zqstdyjstb
                            if (!fc.Contains("zqstdyjstb"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                            // 行政区名称
                            string zName = fcName.GetWord("中文");
                            string zCode = dict_xzq.ContainsKey(zName) ? dict_xzq[zName] : "";

                            pw.AddMessageMiddle(0, $"{zCode}{zName}", Brushes.Gray);


                            string zqstdyjstb = fc;

                            // 计算字段
                            Arcpy.CalculateField(zqstdyjstb, "TBSC", "'年度变更数据变化'");
                            Arcpy.CalculateField(zqstdyjstb, "BZ", "''");

                            string dltb = zqstdyjstb.Replace(year, "2021").Replace("zqstdyjstb", "zqstdy");
                            // 更新村庄名称和代码
                            UpdataDLMC(zqstdyjstb, dltb);

                        }
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }

        }

        private async void btn_jstb_fd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\zqstdyjstb";

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");
                        string gdb = $@"{inputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            // 找zqstdyjstb
                            if (!fc.Contains("zqstdyjstb"))
                            {
                                continue;
                            }

                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..];

                            pw.AddMessageMiddle(0, $"{fcName}", Brushes.Gray);

                            // 通过模板更新所有字段
                            string tem = $@"{defGDB}\tem";
                            Arcpy.CopyFeatures(model, tem);
                            Arcpy.Append(fc, tem);
                            Arcpy.CopyFeatures(tem, fc);

                        }
                    }
                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private void UpdataDLMC(string fc, string dltb)
        {

            // 获取原始图层和标识图层的要素类
            FeatureClass originFeatureClass = fc.TargetFeatureClass();
            FeatureClass identityFeatureClass = dltb.TargetFeatureClass();

            // 获取目标图层和源图层的要素游标
            using RowCursor originCursor = originFeatureClass.Search();

            // 遍历源图层的要素
            while (originCursor.MoveNext())
            {

                using Feature originFeature = (Feature)originCursor.Current;

                // 获取源要素的几何
                ArcGIS.Core.Geometry.Geometry originGeometry = originFeature.GetShape();

                // 创建空间查询过滤器，以获取与源要素有重叠的目标要素
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry = originGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // 在目标图层中查询与源要素重叠的要素
                using (RowCursor identityCursor = identityFeatureClass.Search(spatialFilter))
                {
                    while (identityCursor.MoveNext())
                    {
                        double area = 0;

                        using Feature identityFeature = (Feature)identityCursor.Current;
                        // 获取目标要素的几何
                        ArcGIS.Core.Geometry.Geometry identityGeometry = identityFeature.GetShape();

                        // 计算源要素与目标要素的重叠面积
                        ArcGIS.Core.Geometry.Geometry intersection = GeometryEngine.Instance.Intersection(originGeometry, identityGeometry);

                        // 如果重叠面积大于当前最大重叠面积，则更新最大重叠面积和目标要素
                        if (intersection is not null)
                        {
                            double overlapArea = Math.Round((intersection as ArcGIS.Core.Geometry.Polygon).Area, 2);

                            if (overlapArea > area)
                            {
                                // 赋值
                                originFeature["DLMC"] = identityFeature["DLMC"];
                                originFeature["DLBM"] = identityFeature["DLBM"];

                                area = overlapArea;
                            }
                        }
                    }
                }

                // 更新源图层中的源要素
                originFeature.Store();

            }
        }


        // 指标汇总
        private void btn_cal_Click(object sender, RoutedEventArgs e)
        {



        }

        private async void btn_cs_fdUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【生成初始范围】", Brushes.Blue);

                    // 模板
                    string model = @"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1-输入数据\标准数据库.gdb\zqcsfw";

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}", Brushes.Gray);

                        string xzq = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\参照图层.gdb\XZQ";

                        // 原始dyd
                        string dyd = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\350524安溪县({year}).gdb\data\CZCDYD";
                        string fcPath = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqcsfw";
                        string fcPath2 = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqcsfw2";

                        Arcpy.Select(dyd, fcPath2, "CZCLX IN ('202', '202A')");

                        // 通过模板更新所有字段
                        string tem = $@"{defGDB}\tem";
                        Arcpy.CopyFeatures(model, tem);
                        Arcpy.Append(fcPath2, tem);
                        Arcpy.CopyFeatures(tem, fcPath2);

                        // 计算字段值
                        // 重新计算字段
                        Arcpy.CalculateField(fcPath2, "SMC", "'福建省'");
                        Arcpy.CalculateField(fcPath2, "JSMJ", "round(!Shape_Area!,2)");
                        Arcpy.CalculateField(fcPath2, "BZ", "''");
                        // 空间更新
                        ComboTool.SetValueBySpatialPosition(fcPath2, xzq, [["XZQDM", "XZQDM"], ["XZQMC", "XZQMC"]]);

                        Arcpy.CopyFeatures(fcPath2, fcPath, xyTolerance: "0.001 Meter", xyResolution: "0.0001 Meter");
                        Arcpy.Delect(fcPath2);
                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_cs_inSt_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【初始是否都在实体地域内】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");

                        string zqcsfw = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqcsfw";
                        string zqstdy = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";

                        // 擦除
                        string erase = $@"{defGDB}\erase_{year}";
                        Arcpy.Erase(zqcsfw, zqstdy, erase);

                        var fCount = erase.GetFeatureCount();

                        if (fCount == 0)
                        {
                            pw.AddMessageMiddle(0, $"     错误图斑数量：{fCount}", Brushes.Gray);
                        }
                        else
                        {
                            List<double> areas = GisTool.GetDoubleFieldValuesFromPath(erase, "shape_area");
                            double maxArea = areas.Max();
                            pw.AddMessageMiddle(0, $"     错误图斑数量：{fCount}，最大面积{maxArea}", Brushes.Gray);
                        }

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_st_ydhl_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【纳入的地类是否合规】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");

                        string zqcsfw = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqcsfw";
                        string zqstdy = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";

                        // 擦除
                        string erase2 = $@"{defGDB}\erase2_{year}";
                        Arcpy.Erase(zqstdy, zqcsfw, erase2);
                        // 选择
                        string select2 = $@"{defGDB}\select2_{year}";
                        Arcpy.Select(erase2, select2, "DLBM NOT IN ('0508', '05H1', '0601', '0701', '0702','0809', '0810', '0810A', '08H1', '08H2', '08H2A', '09', '1001','1002', '1003', '1004', '1005', '1006','1007', '1008','1009','1107','1107A',''1109')");

                        var fCount = select2.GetFeatureCount();

                        pw.AddMessageMiddle(0, $"     错误图斑数量：{fCount}", Brushes.Gray);

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_cs_kd_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【初始范围空洞是否被填充】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");

                        string zqcsfw = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqcsfw";
                        string zqstdy = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";
                        // 空洞
                        string cave = $@"{defGDB}\cave_{year}";
                        ComboTool.GetCave(zqcsfw, cave);

                        // 裁剪
                        string clip_fc = $@"{defGDB}\clip_fc_{year}";
                        Arcpy.Clip(zqstdy, cave, clip_fc);

                        var fCount = clip_fc.GetFeatureCount();

                        if (fCount == 0)
                        {
                            pw.AddMessageMiddle(0, $"     错误图斑数量：{fCount}", Brushes.Gray);
                        }
                        else
                        {
                            List<double> areas = GisTool.GetDoubleFieldValuesFromPath(clip_fc, "shape_area");
                            double maxArea = areas.Max();
                            pw.AddMessageMiddle(0, $"     错误图斑数量：{fCount}，最大面积{maxArea}", Brushes.Gray);
                        }

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_topo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【拓扑重叠】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");

                        string gdb = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..].Replace("安溪县", "");

                            // 拓扑重叠
                            string defGDB = Project.Current.DefaultGeodatabasePath;
                            ComboTool.TopologyCheck(fc, ["Must Not Overlap (Area)"], defGDB);

                            string polygon = $@"{defGDB}\TopErr_poly";
                            string polyline = $@"{defGDB}\TopErr_line";
                            string point = $@"{defGDB}\TopErr_point";

                            List<string> errs = new List<string>() { polygon, polyline, point };

                            long errCount = 0;

                            foreach (var err in errs)
                            {

                                var fCount = err.GetFeatureCount();

                                errCount += fCount;
                            }


                            if (errCount > 0)
                            {
                                pw.AddMessageMiddle(0, $"           {fcName}_重叠错误：{errCount}", Brushes.Red);
                            }
                            else
                            {
                                pw.AddMessageMiddle(0, $"           {fcName}_重叠错误：{errCount}", Brushes.Gray);
                            }

                        }

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }


        private async void btn_area_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【小于1平方米图斑】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");

                        string gdb = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..].Replace("安溪县", "");

                            // 拓扑重叠
                            string defGDB = Project.Current.DefaultGeodatabasePath;
                            // 选择
                            string select3 = $@"{defGDB}\select3_{year}";
                            Arcpy.Select(fc, select3, "Shape_Area < 1");

                            var fCount = select3.GetFeatureCount();
                            pw.AddMessageMiddle(0, $"           {fcName}_面积小于1的图斑：{fCount}", Brushes.Gray);

                        }

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_zz_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【年度增减图斑检查】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        int initYear = int.Parse(year);
                        int lastYear = initYear - 1;
                        // 2021年没有上一年度数据
                        if (initYear == 2021)
                        {
                            continue;
                        }

                        pw.AddMessageMiddle(0, $"{year}");
                        string initSt = $@"{newInputFolder}\350524安溪县\350524安溪县{initYear}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";
                        string lastSt = $@"{newInputFolder}\350524安溪县\350524安溪县{lastYear}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";
                        string zjtb = $@"{newInputFolder}\350524安溪县\350524安溪县{initYear}\1矢量数据\350524安溪县.gdb\安溪县zqstdyzjtb";
                        string jstb = $@"{newInputFolder}\350524安溪县\350524安溪县{initYear}\1矢量数据\350524安溪县.gdb\安溪县zqstdyjstb";

                        // 增加图斑检查
                        string erase01 = $@"{defGDB}\erase01";
                        Arcpy.Erase(initSt, lastSt, erase01);
                        string symdiff01 = $@"{defGDB}\symdiff01_{initYear}";
                        Arcpy.SymDiff(erase01, zjtb, symdiff01);

                        var fCount = symdiff01.GetFeatureCount();

                        pw.AddMessageMiddle(0, $"           {initYear}_增加图斑有误：{fCount}", Brushes.Gray);

                        // 减少图斑检查
                        string erase02 = $@"{defGDB}\erase02";
                        Arcpy.Erase(lastSt, initSt, erase02);
                        string symdiff02 = $@"{defGDB}\symdiff02_{initYear}";
                        Arcpy.SymDiff(erase02, jstb, symdiff02);

                        var fCount2 = symdiff02.GetFeatureCount();

                        pw.AddMessageMiddle(0, $"           {initYear}_减少图斑有误：{fCount2}", Brushes.Gray);


                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_multiPart_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【多部件检查】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");

                        string gdb = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..].Replace("安溪县", "");

                            int fCount = 0;

                            // 获取原始图层和标识图层的要素类
                            FeatureClass originFeatureClass = fc.TargetFeatureClass();
                            // 获取目标图层和源图层的要素游标
                            using RowCursor originCursor = originFeatureClass.Search();
                            // 遍历源图层的要素
                            while (originCursor.MoveNext())
                            {
                                using Feature feature = (Feature)originCursor.Current;
                                Polygon polygon = feature.GetShape() as Polygon;
                                // 获取面要素的所有点（内外环）
                                List<List<MapPoint>> mapPoints = polygon.MapPointsFromPolygon();

                                List<List<MapPoint>> newPoints = new List<List<MapPoint>>();
                                // 挑选合适的
                                foreach (List<MapPoint> mapPoint in mapPoints)
                                {
                                    // 判断顺逆时针
                                    bool isClockwise = mapPoint.IsColckwise();
                                    if (isClockwise)
                                    {
                                        newPoints.Add(mapPoint);
                                    }
                                }

                                if (newPoints.Count > 1)
                                {
                                    fCount += 1;
                                }

                            }
                            pw.AddMessageMiddle(0, $"           {fcName}_多部件图斑：{fCount}", Brushes.Gray);

                        }

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_geo_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【几何错误检查】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}");

                        string gdb = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb";

                        // 获取 矢量数据
                        List<string> fcs = gdb.GetFeatureClassPathFromGDB();

                        foreach (var fc in fcs)
                        {
                            string fcName = fc[(fc.LastIndexOf(@"\") + 1)..].Replace("安溪县", "");

                            int fCount = 0;

                            // 默认数据库位置
                            string out_table = $@"{Project.Current.DefaultGeodatabasePath}\out_table";
                            Arcpy.CheckGeometry(fc, out_table);

                            // 获取ID字段
                            string IDField = fc.TargetIDFieldName();

                            using Table table = out_table.TargetTable();
                            using RowCursor rowCursor = table.Search();
                            while (rowCursor.MoveNext())
                            {
                                using Row row = rowCursor.Current;
                                // OID值
                                string OID = row["FEATURE_ID"].ToString();
                                // PROBLEM值
                                string problem = row["PROBLEM"].ToString();

                                fCount++;

                            }
                            pw.AddMessageMiddle(0, $"           {fcName}_几何错误：{fCount}", Brushes.Gray);

                        }

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_cs_202_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【初始范围是否符合202】", Brushes.Blue);


                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}", Brushes.Gray);

                        string xzq = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\参照图层.gdb\XZQ";

                        // 原始dyd
                        string dyd_202 = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\350524安溪县({year}).gdb\data\CZCDYD_202";
                        string fcPath = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqcsfw";

                        string symdiff = $@"{defGDB}\symdiff";
                        Arcpy.SymDiff(fcPath, dyd_202, symdiff);

                        long fCount = symdiff.GetFeatureCount();

                        if (fCount == 0)
                        {
                            pw.AddMessageMiddle(0, $"     错误图斑数量：{fCount}", Brushes.Gray);
                        }
                        else
                        {
                            List<double> areas = GisTool.GetDoubleFieldValuesFromPath(symdiff, "shape_area");
                            double maxArea = areas.Max();
                            pw.AddMessageMiddle(0, $"     错误图斑数量：{fCount}，最大面积{maxArea}", Brushes.Gray);
                        }
                    }

                    

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private async void btn_st_fdUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【实体地域字段更新】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        pw.AddMessageMiddle(0, $"{year}", Brushes.Gray);

                        string xzq2 = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\参照图层.gdb\XZQ2";
                        string DLTB = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\参照图层.gdb\DLTB";

                        string stdy = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";
                        string csfw = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqcsfw";

                        // 空间更新
                        ComboTool.SetValueBySpatialPosition(stdy, xzq2, [["XZQDM", "XZQDM"], ["XZQMC", "XZQMC"]]);
                        ComboTool.SetValueBySpatialPosition(stdy, DLTB, [["JCWDM", "ZLDWDM"], ["JCWMC", "ZLDWMC"], ["DLBM", "DLBM"], ["DLMC", "DLMC"]]);

                        Arcpy.CalculateField(stdy, "SMC", "'福建省'");

                        // 迭代次数
                        SetValueDD(stdy, csfw);

                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }

        private void SetValueDD(string stdy, string csfw)
        {
            // 获取原始图层和标识图层的要素类
            FeatureClass originFeatureClass = stdy.TargetFeatureClass();
            FeatureClass identityFeatureClass = csfw.TargetFeatureClass();

            // 如果两个图层使用的空间参考不同，投影到一致
            SpatialReference sr_ori = originFeatureClass.GetDefinition().GetSpatialReference();
            SpatialReference sr_iden = identityFeatureClass.GetDefinition().GetSpatialReference();

            // 获取目标图层和源图层的要素游标
            using RowCursor originCursor = originFeatureClass.Search();

            // 遍历源图层的要素
            while (originCursor.MoveNext())
            {

                using Feature originFeature = (Feature)originCursor.Current;

                // 获取源要素的几何
                Geometry originGeometry = originFeature.GetShape();

                // 创建空间查询过滤器，以获取与源要素有重叠的目标要素
                SpatialQueryFilter spatialFilter = new SpatialQueryFilter
                {
                    FilterGeometry = originGeometry,
                    SpatialRelationship = SpatialRelationship.Intersects
                };

                // 在目标图层中查询与源要素重叠的要素
                using RowCursor identityCursor = identityFeatureClass.Search(spatialFilter);
                while (identityCursor.MoveNext())
                {
                    using Feature identityFeature = (Feature)identityCursor.Current;
                    // 获取目标要素的几何
                    Geometry identityGeometry = identityFeature.GetShape();

                    // 计算源要素与目标要素的重叠面积
                    Geometry intersection = GeometryEngine.Instance.Intersection(originGeometry, identityGeometry);
                    double overlapArea = Math.Round((intersection as Polygon).Area, 2);

                    // 如果重叠面积
                    if (overlapArea > 0)
                    {
                        originFeature["RepeatNum"] = "0";
                        // 更新源图层中的源要素
                        originFeature.Store();
                    }
                }

            }
        }
        // 生成增减图斑
        private async void btn_zztb_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 打开进度框
                ProcessWindow pw = UITool.OpenProcessWindow(processwindow, tool_name);
                pw.AddMessageTitle(tool_name);
                await QueuedTask.Run(() =>
                {
                    pw.AddMessageMiddle(0, $"【生成增减图斑】", Brushes.Blue);

                    foreach (var year in years)
                    {
                        int year_init = int.Parse(year);
                        int yeart_last = year_init - 1;
                        if (year_init == 2021)
                        {
                            continue;
                        }

                        pw.AddMessageMiddle(0, $"{year}", Brushes.Gray);

                        

                        string xzq2 = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\参照图层.gdb\XZQ2";
                        string DLTB = $@"D:\【工作项目】\【总规】\安溪国土空间规划\【镇区划定】\1基础资料\参照图层.gdb\DLTB";

                        
                        string stdy_init = $@"{newInputFolder}\350524安溪县\350524安溪县{year_init}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";
                        string stdy_last = $@"{newInputFolder}\350524安溪县\350524安溪县{yeart_last}\1矢量数据\350524安溪县.gdb\安溪县zqstdy";


                        string tem_fc = $@"{defGDB}\tem_fc";
                        string zjtb = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqstdyzjtb";
                        string jstb = $@"{newInputFolder}\350524安溪县\350524安溪县{year}\1矢量数据\350524安溪县.gdb\安溪县zqstdyjstb";
                        // 增加图斑
                        Arcpy.Erase(stdy_init, stdy_last, tem_fc);
                        Arcpy.MultipartToSinglepart(tem_fc, zjtb);
                        // 减少图斑
                        Arcpy.Erase(stdy_last, stdy_init, tem_fc);
                        Arcpy.MultipartToSinglepart(tem_fc, jstb);

                        // 更新字段_增加图斑
                        Arcpy.CalculateField(zjtb, "SMC", "'福建省'");


                        // 更新字段_增加图斑
                        Arcpy.CalculateField(jstb, "SMC", "'福建省'");


                    }

                });
                pw.AddMessageEnd();
            }
            catch (Exception ee)
            {
                MessageBox.Show(ee.Message + ee.StackTrace);
                return;
            }
        }
    }
}
